package com.ponhu.ea2.goodsCenter.provider.config;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ponhu.ea2.enums.SyncAppletTypeEnum;
import com.ponhu.ea2.goodsCenter.provider.service.GoodsDataCreateorupdateLogService;
import com.ponhu.ea2.goodsCenter.provider.utils.DingTalkHandler;
import com.ponhu.ea2.properties.GoodsProperties;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.BooleanUtils;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author luyu
 * @create 2022-03-23 16:25
 */
@Slf4j
@Component
public class RabbitTemplateConfig implements RabbitTemplate.ReturnCallback,RabbitTemplate.ConfirmCallback{

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Resource
    private GoodsDataCreateorupdateLogService goodsDataCreateorupdateLogService;

    @Resource
    DingTalkHandler dingTalkHandler;

    @Resource
    GoodsProperties goodsProperties;

    @PostConstruct
    public void initRabbitTemplate(){
        rabbitTemplate.setConfirmCallback(this);
        rabbitTemplate.setReturnCallback(this);
    }

    /**
     * 未能到达queue中
     * @param message
     * @param replyCode
     * @param replyText
     * @param exchange
     * @param routingKey
     */
    @Override
    public void returnedMessage(Message message, int replyCode, String replyText, String exchange, String routingKey) {
        log.info("推送会员小程序失败,未能到达消息队列中,类型为:{},货品编码为:{}",replyCode,replyText);
        // 根据routingkey判断type
        Integer type = null;
        if(routingKey.equals(goodsProperties.getRoutingKeyMap().get("priceKey"))){
            type = SyncAppletTypeEnum.GOODS_PRICE.getCode();
        }else if(routingKey.equals(goodsProperties.getRoutingKeyMap().get("statusKey"))){
            type = SyncAppletTypeEnum.GOODS_STATUS.getCode();
        }else {
            type = SyncAppletTypeEnum.PH_INVENTORY_DATA.getCode();
        }
        JSONArray list =  JSONArray.parseArray(new String(message.getBody()));
        Integer finalType = type;
        list.stream().forEach( item -> {
            goodsDataCreateorupdateLogService.saveLog(
                    "Applet",
                    "推送会员小程序失败",
                    ((JSONObject)item).getString("inventoryCode"),
                    finalType.toString());
            String msg = dingTalkHandler.getMsgForApplet(finalType,
                    ((JSONObject)item).getString("inventoryCode"),"消息队列不存在");
            dingTalkHandler.sendMsg(msg, new ArrayList());
        });
    }

    /**
     * 未能到达服务器处理
     * @param correlationData
     * @param b
     * @param s
     */
    @Override
    public void confirm(CorrelationData correlationData, boolean b, String s) {
        if(BooleanUtils.isFalse(b)){
            log.info("推送会员小程序失败,未到达rabbitMQ服务器,类型为:{},货品编码为:{}",
                    correlationData.getReturned().getReplyCode(),
                    correlationData.getReturned().getReplyText());
            List list =  JSONObject.parseArray(correlationData.getReturned().getReplyText());
            list.stream().forEach(item -> {
                goodsDataCreateorupdateLogService.saveLog(
                        "Applet",
                        "推送会员小程序失败",
                        item.toString(),
                        String.valueOf(correlationData.getReturned().getReplyCode()));
                String msg = dingTalkHandler.getMsgForApplet(correlationData.getReturned().getReplyCode(), item.toString(),"消息服务器异常");
                dingTalkHandler.sendMsg(msg, new ArrayList());
            });

        }
    }
}
